<?php
/**
 * Created by PhpStorm.
 * User: 爱尔
 * Date: 2020/9/28
 * Time: 11:31
 */

namespace app\admin\model;

use think\Model;

class GroupmindModel extends Model {
    protected $name = 'ht_groupmind';
    protected $autoWriteTimestamp = true;//时间自动更新 create_time ,update_time
    protected $field = true;

    public function getMind(){
        return $this->hasMany("MindModel",'groupmind_id','id');
    }

    /**
     * 创建思维导图时，创建默认的节点
     */
    public function createDefaltNote(){

        $list=array(
            array('id'=>'root','isroot'=>'true','topic'=>'项目报价单','isreadonly'=>true,'expanded'=>true),
            array('id'=>'sub1',"parentid"=>"root",'topic'=>'硬件设备','direction'=>'left'),
            array('id'=>'sub2',"parentid"=>"root",'topic'=>'功能模块','direction'=>'right'),
        );

        return $list;
    }
    /**
     * 保存数据
     * @param $param
     * @return mixed
     */
    public function saveData($param,$is_manage){
        $group_data = array('isdelete'=>0);
        foreach ($param as $kay=>$value){
            $is_h = strpos($value['topic'],"/");
            if($is_h){
                $value['topic'] = substr($value['topic'],0,$is_h);
            }
            if($value['id'] == 'root' && $value['isroot'] == 'true'){
                $group_data['name'] = $value['topic'];
            }
        }
        $this->startTrans();
        $result = $this->allowField(true)->save($group_data);

        if($result){
            $id = $this->id;
        }else{
            $this->rollback();
            $ret['data'] = '';
            $ret['code'] = -1;
            $ret['msg']  = '保存失败';
            $this->commit();
            return $ret;
        }

        foreach ($param as $k=>$v){
            $param[$k]['groupmind_id'] = $id;
            $param[$k]['mind_id'] = $v['id'];
            if($is_manage == 0){
                unset($param[$k]['price']);
                unset($param[$k]['combo1']);
                unset($param[$k]['combo2']);
                unset($param[$k]['combo3']);
            }
            unset($param[$k]['id']);
        }
        //dump($add);die;
        if($id!='' && !empty($param)){
            $model = new MindModel();
            $result = $model->allowField(true)->saveAll($param);
            //echo $this->getLastSql();
            if($result){
                $ret['data'] = '';
                $ret['code'] = 0;
                $ret['msg']  = '保存成功';
            }else{
                $this->rollback();
                $ret['data'] = '';
                $ret['code'] = -1;
                $ret['msg']  = '保存失败';
            }
        }else{
            $this->rollback();
            $ret['data'] = '';
            $ret['code'] = -1;
            $ret['msg']  = '保存失败';
        }
        $this->commit();
        return $ret;
    }

    /**
     * 编辑数据
     */
    public function updataData($param,$is_manage){
        $group_data = array();
        $group_id = null;
        $status = 0;
        foreach ($param as $kay=>$value){
            $is_h = strpos($value['topic'],"/");
            if($is_h){
                $value['topic'] = substr($value['topic'],0,$is_h);
            }
            if($value['id'] == 'root'){
                $group_data['name'] = $value['topic'];
                $group_data['update_time'] = time();
                $group_id = $value['groupmind_id'];
            }
            if($group_id == null && $status == 0){
                $group_id = $value['groupmind_id'];
                $status == 1;
            }
        }

        $result = $this->allowField(true)->save($group_data,['id'=>$group_id]);
        $this->startTrans();

        $id = $group_id;
        if(!$result){
            $this->rollback();
            $ret['data'] = '';
            $ret['code'] = -1;
            $ret['msg']  = '保存失败';
            return $ret;
        }

        $add = [];
        $updata = [];
        $delete = [];

        $temp_id = null;
        foreach ($param as $k=>$v){

            if($is_manage == 0){
                unset($param[$k]['price']);
                unset($param[$k]['combo1']);
                unset($param[$k]['combo2']);
                unset($param[$k]['combo3']);
            }
            if(!empty($v['mind_id'])){
                $temp_id = $v['mind_id'];
                $v['mind_id'] = $v['id'];
                $v['id']=$temp_id;
                unset($v['create_time']);
                unset($v['update_time']);
                //$v['update_time'] = time();
                //$v['edit_node_user'] = session('username');
                if(isset($v['edit_node_user_select']) && $v['edit_node_user_select'] == 'true'){
                    $v['update_time'] = time();
                    if(!empty(session('username'))){
                        $v['edit_node_user'] = session('username');
                    }else{
                        $v['edit_node_user'] = '前端用户';
                    }

                }
                $updata[] = $v;
            }else{
                $v['groupmind_id'] = $id;
                $v['mind_id'] = $v['id'];
                unset($v['id']);
                if(isset($v['add_node_user_select']) && $v['add_node_user_select'] == 'true'){
                    $v['create_time'] = time();
                    $v['update_time'] = time();
                    if(!empty(session('username'))){
                        $v['add_node_user'] = session('username');
                    }else{
                        $v['add_node_user'] = '前端用户';
                    }
                }
                $add[] = $v;
            }
        }
        //dump($updata);exit;
        if($id!=''){
            $model = new MindModel();
            $old_date = MindModel::where('groupmind_id',$id)->where('isdelete','0')->column('id');
            if(!empty($old_date)){
                foreach ($updata as $key => $value){
                    if(in_array($value['id'],$old_date)){
                        $old_key = array_search($value['id'],$old_date);
                        unset($old_date[$old_key]);
                    }
                }
            }
            $delete = $old_date;
            $result = $model->allowField(true)->saveAll($updata);
            //前端删除的节点，数据库中也要同步删除

            if(!empty($delete)){
                $maps["id"] = array("in",$delete);
                MindModel::where($maps)->delete(true);
            }

            if($result!='' && !empty($add)){
                $result = $model->allowField(true)->saveAll($add);

                if(!$result){
                    $this->rollback();
                    $ret['data'] = '';
                    $ret['code'] = -1;
                    $ret['msg']  = '保存失败';
                    $this->commit();
                    return $ret;
                }
            }
            if($result){
                $ret['data'] = '';
                $ret['code'] = 0;
                $ret['msg']  = '保存成功';
            }else{
                $this->rollback();
                $ret['data'] = '';
                $ret['code'] = -1;
                $ret['msg']  = '保存失败';
            }
        }else{
            $this->rollback();
            $ret['data'] = '';
            $ret['code'] = -1;
            $ret['msg']  = '保存失败';
        }

        $this->commit();
        return $ret;
    }

    /**
     * 获取数据
     */
    public function getMindData($id,$manage){
        $where = "isdelete=0";
        if($id){
            $where .= " and id=$id";
        }
        $result = $this->with('getMind')->where($where)->select();
        //dump($result);exit;
        $temp = '';
        if($result){
            foreach($result as $key=>$v){
                foreach ($v->get_mind as $k1=>$v1){
                    $no_manage = strpos($v1->topic,"/");
                    if($no_manage){
                        $v1->topic = substr($v1->topic,0,$no_manage);

                    }
                    if($manage == 1){
                        $v1->topic = $v1->topic.'/'.$v1->price;
                    }else{
                        $v1->topic = $v1->topic;
                    }
                    /*$v1->combo1 =  $v1->combo1 != 1 ? 'fasle' : 'true';
                    $v1->combo2 =  $v1->combo2 != 1 ? 'fasle' : 'true';
                    $v1->combo3 =  $v1->combo3 != 1 ? 'fasle' : 'true';*/
                    //dump($this->getLastSql());
                    $temp = $v1->id;
                    $v1->id =  $v1->mind_id;
                    $v1->mind_id = $temp;
                }
                $list = $v->toArray();
            }
            $header_array = array(
                "id" => $list["id"],
                "name" => $list["name"],
                "company_addressee" => $list["company_addressee"],
                "company_sender" => $list["company_sender"],
                "sender" => $list["sender"],
                "mobile" => $list["mobile"],
                "tel" => $list["tel"],
                "subject" => $list["subject"],
                "address" => $list["address"],
                "date" => date('Y-m-d',strtotime($list["date"])),
                "is_edit_mind" => $list["is_edit_mind"]
            );
            $ret['header'] = $header_array;
            $ret['data'] = $list['get_mind'];
            $ret['code'] = 0;
            $ret['msg']  = '获取数据成功！';
        }else{
            $ret['header'] = array();
            $ret['data'] = '';
            $ret['code'] = -1;
            $ret['msg']  = '获取数据失败！';
        }
        return $ret;
    }

}